<template>
  <div class="map">
    <div class="mapClass" id="mapId">
      <div class="button">
        <!-- <button class="button_detail" @click="bigger">放 大</button>
        <button class="button_detail" @click="smaller">缩 小</button> -->
        <button class="button_detail" @click="gobackHome">
          返回初始定位
        </button>
        <button class="button_detail" @click="loadingPoint">
          加载排污口1
        </button>
        <button class="button_detail" @click="loadingImg">
          加载排污口2
        </button>
        <!-- <button class="button_detail" @click="loadingWfs">
          加载WFS服务
        </button> -->
        <button class="button_detail" @click="clearPoint">
          清除点位
        </button>
        <button class="button_detail" @click="drawFlat">
          画面
        </button>
        <button class="button_detail" @click="drawCircle">
          画圆
        </button>
        <button class="button_detail" @click="drawLine">
          画线
        </button>
        <button class="button_detail" @click="clearFlat">
          退出绘制
        </button>
      </div>
      <!-- <div class="dialog" v-if="dialogShow">
        <div class="closeDialog" @close="dialogShow = false">X</div>
        <div>name: {{ popName }}</div>
      </div> -->
    </div>
  </div>
</template>

<script>
import 'ol/ol.css'
import Map from 'ol/Map'
import View from 'ol/View'
import VectorLayer from 'ol/layer/Vector'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import { Feature } from 'ol'
import { Point } from 'ol/geom'
import VectorSource from 'ol/source/Vector'
import Icon from 'ol/style/Icon'
import dm1 from '@/assets/dm1.png'
import { Circle, Fill, Style } from 'ol/style'
import WFS from 'ol/format/WFS'
import GeoJSON from 'ol/format/GeoJSON'
import Stroke from 'ol/style/Stroke'
import Draw from "ol/interaction/Draw"
import WKT from 'ol/format/WKT';
import {fromCircle} from 'ol/geom/Polygon';

export default {
  name: 'HelloWorld',
  data () {
    return {
      dialogShow: false,
      openMap: null,
      layers: [], //图层数组
      // 固定点位数组  demo
      pointList: [
        {
          address: '哈尔滨市人民政府 ',
          county: '松北区',
          hylb: '啤酒制造',
          jd: '126.53',
          psl: '3000吨',
          pszxbz: '19821—2005',
          pwxk: '哈尔滨市人民政府',
          qyName: '哈尔滨市人民政府',
          sczt: '在产',
          wd: '45.8',
        },
        {
          address: '哈尔滨火车站 ',
          county: '道里区',
          hylb: '啤酒制造',
          jd: '126.63',
          psl: '3000吨',
          pszxbz: '19821—2005',
          pwxk: '哈尔滨火车站(重点管理)',
          qyName: '哈尔滨火车站',
          sczt: '在产',
          wd: '45.76',
        },
        {
          address: '哈尔滨东站 ',
          county: '道外区',
          hylb: '啤酒制造',
          jd: '126.71',
          psl: '3000吨',
          pszxbz: '19821—2005',
          pwxk: '哈尔滨东站',
          qyName: '哈尔滨东站',
          sczt: '在产',
          wd: '45.79',
        },
      ],
      url: 'http://36.138.129.34:6080/geoserver/wfs',
      showWorkMenu: true,
      draw: null,
      vectorLayer: null, //全局总图层名称
      vectorSource: null, //全局图层资源
    }
  },
  mounted () {
    this.initMap()
  },
  methods: {
    // 地图初始化
    initMap () {
      console.log('初始化');
      
      this.openMap = new Map({
        layers: [
          new TileLayer({
            source: new XYZ({
              url:
                'http://t' +
                Math.round(Math.random() * 7) +
                '.tianditu.com/DataServer?T=cva_c&x={x}&y={y}&l={z}&tk=1d109683f4d84198e37a38c442d68311', //天地图-标注地址
              projection: 'EPSG:4326', //标注的坐标系
              wrapX: false,
            }),
            zIndex: 1,
          }),
          new TileLayer({
            source: new XYZ({
              url:
                'http://t' +
                Math.round(Math.random() * 7) +
                '.tianditu.com/DataServer?T=vec_c&x={x}&y={y}&l={z}&tk=1d109683f4d84198e37a38c442d68311',
              projection: 'EPSG:4326',
              wrapX: false,
            }),
            zIndex: 0,
          }),
        ],
        view: new View({
          center: [126.5, 45.8], //设置初始化地图中心点位
          zoom: 12, //地图初始化放大级别
          projection: 'EPSG:4326',
        }),
        target: 'mapId',
      })
      // 给地图绑定⿏标移动事件，让光标移动到要素上的时候改变样式
      // this.openMap.on('pointermove', function (e) {
      //   var pixel = this.openMap.getEventPixel(e.originalEvent);
      //   var hit = this.openMap.hasFeatureAtPixel(pixel);
      //   this.openMap.getTargetElement().style.cursor = hit ? 'pointer' : '';
      // });
    },
    //地图放大、缩小、定位初始位置公共方法
    zoomMap (type, num) {
      const view = this.openMap.getView()
      if (type === 'setZoom') {
        const zoom = view.getZoom()
        view.setZoom(zoom + num)
        return
      }
      view.animate({
        center: [126.5, 45.8],
        zoom: 12,
        duration: 1000, //动画的持续时间
      })
    },
    // 放大地图
    bigger () {
      this.zoomMap('setZoom', 1)
    },
    // 缩小地图
    smaller () {
      this.zoomMap('setZoom', -1)
    },
    // 返回初始化定位点
    gobackHome () {
      this.zoomMap()
    },
    // 加载点位公共方法
    // 如果是图片  iconSrc传的为地址，radius为图片伸缩或者点位大小
    createFeatureLayer (iconSrc, radius) {
      let features = []
      this.pointList.forEach((item) => {
        //循环创建点位feature
        let feature = new Feature({
          geometry: new Point([
            parseFloat(item.jd),
            parseFloat(item.wd),
          ]),
          type: '点位',
          data: item,
        })
        features.push(feature)
      })
      //创建source参数
      let source = new VectorSource({
        features: features,
      })
      const style = () => {
        if (iconSrc) {
          return new Style({
            image: new Icon({
              anchor: [0.5, 0.5], //图片偏移量
              scale: radius, //图片大小
              src: dm1, //设置图片
            }),
          })
        } else {
          return new Style({
            image: new Circle({
              fill: new Fill({
                color: 'red',
              }),
              radius: radius || 11.5,
            }),
          })
        }
      }
      //创建layer图层
      let layer = new VectorLayer({
        source: source,
        style: style,
        zIndex: 2,
      })
      this.openMap.addLayer(layer) //将图层加载到底图中
      this.layers.push(layer)
      this.openMap.getView().fit(source.getExtent()) //放大到当前图层
    },
    // 加载排污口  点位
    loadingPoint () {
      this.createFeatureLayer(null, 11.5)
    },
    // 加载排污口  图片
    loadingImg () {
      this.createFeatureLayer(dm1, 0.8)
    },
    // 加载WFS服务
    loadingWfs () {
      console.log('0000')
      const _this = this
      const featureRequest = new WFS().writeGetFeature({
        srsName: 'EPSG:3857',
        featurePrefix: 'hlj',
        featureTypes: ['hejiagou_wangge'],
        outputFormat: 'application/json',
        // filter: _this.likeFilter("pro_name", "黑龙江省" + "*"),
      }) //创建WFS请求
      fetch(this.url, {
        method: 'POST',
        body: new XMLSerializer().serializeToString(featureRequest),
      }) //读取WFS
        .then(function (response) {
          return response.json() //获取GeoJson格式数据
        })
        .then(function (json) {
          const regionFeatures = new GeoJSON().readFeatures(json) //读取GeoJson格式数据
          const wfsVectorSource = new VectorSource({
            features: regionFeatures,
          })
          var shijieLayer = new VectorLayer({
            source: wfsVectorSource,
            style: styleFunctionhs,
          })
          shijieLayer.setZIndex(3)
          _this.openMap.addLayer(shijieLayer)
          _this.openMap
            .getView()
            .fit(shijieLayer.getSource().getExtent()) //将地图放大到该矢量的范围
          _this.layers.push(shijieLayer)
        })
      let styleFunctionhs = function (features) {
        return new Style({
          stroke: new Stroke({
            color: 'rgb(0,0,255)',
            width: 1,
          }),
          fill: new Fill({
            color: 'rgb(0,42,255)',
          }),
          text: new Text({
            text: features.get('名称'),
            font: 'bold 12px comic sans ms',
            //textBaseline: 'top',
            fill: new Fill({
              color: '#777777',
            }),
          }),
        })
      }
    },
    // 清除地图点位信息
    clearPoint () {
      this.layers.forEach((item) => {
        this.openMap.removeLayer(item)
      })
    },
    // 添加绘制公共方法
    addInteraction (type) {
      // 添加交互绘制控件
      this.vectorSource = new VectorSource({
        wrapX: false
      })
      // 矢量图层   绘制完成时显示的图层
      this.vectorLayer = new VectorLayer({
        source: this.vectorSource,
        style: new Style({
          stroke: new Stroke({
            color: 'rgba(41, 85, 230, 0.4)',
            width: 5
          }),
          fill: new Fill({
            color: 'rgba(41, 85, 230, 0.4)',
          })
        })
      })
      // 绘制时的图层
      this.draw = new Draw({
        source: this.vectorSource,
        type: type,
      });
      this.openMap.addInteraction(this.draw);
      // 绘制完成
      this.draw.on('drawend', (e) => {
        this.openMap.removeInteraction(this.draw)
        this.openMap.addLayer(this.vectorLayer)
        // this.$set(this.vectorLayer, 'strokeColor', '#2955e6')
        // this.$set(this.vectorLayer, 'width', 5)
        // this.$set(this.vectorLayer, 'FillColor', '#2955e6')
        // this.$set(this.vectorLayer, 'featureText', '')
        // this.$set(this.vectorLayer, 'scaleText', 0.8)
        // this.$set(this.vectorLayer, 'offsetYText', -20)
        // this.$set(this.vectorLayer, 'offsetXText', 0)
        // this.$set(this.vectorLayer, 'FillTextLabel', 'rgba(0,0,0,0.5)')
        // this.$set(this.vectorLayer, 'StrokeTextLabel', 'rgba(0,0,0,0.5)')
        // this.$set(this.vectorLayer, 'BackgroundFillLabel', 'rgba(0,0,0,0)')
        // this.$set(this.vectorLayer, 'BackgroundStroke', 'rgba(0,0,0,0)')
        // this.$set(this.vectorLayer, 'featureType', 'polygon')
        // this.$set(this.vectorLayer, 'featureName', this.fe
        this.layers.push(this.vectorLayer)
        this.draw = null
        // console.log('vectorLayer', this.vectorLayer.getSource().getFeatures()); //null
        if(type === 'Circle') {
          // WKT中没有Circle这个几何类型，所以需要将圆类型转化为面类型
          let circleFeature = new fromCircle(e.feature.getGeometry())
          // 转为WKT串，后端需要这样的格式
          let polygonWKTCircle = new WKT().writeGeometry(circleFeature)
          console.log('polygonWKTCircle',polygonWKTCircle);
        }else {
          let polygonWKT = new WKT().writeGeometry(e.feature.getGeometry())
          console.log('polygonWKT',polygonWKT);
        }
      })
    },
    // 绘制画面
    drawFlat () {
      //退出其他绘制
      this.clearFlat();
      this.addInteraction('Polygon')
    },
    // 绘制画圆
    drawCircle () {
      //退出其他绘制
      this.clearFlat();
      this.addInteraction('Circle')
    },
    // 绘制画线
    drawLine() {
      //退出其他绘制
      this.clearFlat();
      this.addInteraction('LineString')
    },
    // 退出绘制模式
    clearFlat () {
      if (this.draw) {
        this.openMap.removeInteraction(this.draw);
        this.draw = null;
      }
    }
  },
}
</script>

<style scoped>
.map {
  width: 100%;
  height: 100%;

  .mapClass {
    width: 100%;
    height: 100%;
    position: relative;

    .button {
      position: absolute;
      top: 5%;
      left: 50%;
      z-index: 3;
      transform: translate(-50%, -50%);
      /* 使用transform平移来使元素居中 */

      .button_detail {
        width: 90px;
        height: 35px;
        margin-left: 5px;
      }
    }
  }
}
</style>
